package mapper

import (
	"cooke-home/common/handle"
	"cooke-home/common/model/base_dto"
	"cooke-home/stock-service/model/dto"
	"cooke-home/stock-service/model/entity"

	"gorm.io/gorm"
)

type StockMapperImpl struct {
	DB        *gorm.DB
	TableName string
}

func NewStockMapperImpl() *StockMapperImpl {
	return &StockMapperImpl{
		DB:        handle.DB,
		TableName: "t_stock",
	}
}

func (sm *StockMapperImpl) Save(stockDto *dto.StockDto) error {
	return sm.DB.Table(sm.TableName).Create(stockDto).Error
}

func (sm *StockMapperImpl) Delete(batchDeleteDto base_dto.BatchDeleteDto) error {
	return sm.DB.Table(sm.TableName).Where("stock_id IN ?", batchDeleteDto.IDs).Delete(&dto.StockDto{}).Error
}

func (sm *StockMapperImpl) Update(stockDto *dto.StockDto) error {
	return sm.DB.Table(sm.TableName).Where("stock_id = ?", stockDto.StockID).Updates(stockDto.StockEntity).Error
}

func (sm *StockMapperImpl) Get(id int64) (*entity.StockEntity, error) {
	var model entity.StockEntity
	err := sm.DB.Table(sm.TableName).Where("stock_id = ?", id).First(&model).Error
	if err != nil {
		return nil, err
	}
	return &model, nil
}

func (sm *StockMapperImpl) GetList(parentId int64) ([]*entity.StockEntity, error) {
	var models []*entity.StockEntity
	err := sm.DB.Table(sm.TableName).Where("parent_id = ?", parentId).Find(&models).Error
	if err != nil {
		return nil, err
	}
	return models, nil
}

func (sm *StockMapperImpl) Clear(stockDto *dto.StockDto) error {
	return sm.DB.Table(sm.TableName).
		Where("stock_id = ?", stockDto.StockID).
		Update("number", 0).Error
}

func (sm *StockMapperImpl) Minus(stockDto *dto.StockDto) error {
	return sm.DB.Table(sm.TableName).
		Where("stock_id = ?", stockDto.StockID).
		Update("number", gorm.Expr("number - ?", stockDto.Number)).Error
}
